package com.tushare.util;

import com.tushare.network.WapRequest;
import com.tushare.network.WapResponse;
import net.minidev.json.JSONObject;
import org.springframework.core.ParameterizedTypeReference;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpMethod;
import org.springframework.http.ResponseEntity;
import org.springframework.web.client.RestTemplate;

public class ServiceUtil {
    private static final String API_URL = "http://api.tushare.pro";
    private WapRequest params;

    public void initWapRequest(String apiName) {
        if (params == null) {
            params = new WapRequest();
        }
        params.init(apiName);
    }

    public void appendField(String fieldName, Object fieldValue) {
        JSONObject jsonObject = params.getParams();
        if (jsonObject == null) {
            jsonObject = new JSONObject();
            params.setParams(jsonObject);
        }
        jsonObject.appendField(fieldName, fieldValue);
    }

    public WapResponse.WapData getNetworkData(RestTemplate restTemplate) {
        HttpHeaders httpHeaders = new HttpHeaders();
        HttpEntity<WapRequest> entity = new HttpEntity<>(params, httpHeaders);
        ParameterizedTypeReference<WapResponse> typeRef = new ParameterizedTypeReference<>() {
        };
        try {
            ResponseEntity<WapResponse> responseEntity = restTemplate.exchange(API_URL, HttpMethod.POST, entity, typeRef);
            WapResponse body = responseEntity.getBody();
            return body == null ? null : body.getData();
        } catch (Exception e) {
            return null;
        }
    }
}
